package com.ybkj.o2o.mc.manager.impl;

import com.ybkj.o2o.mc.common.AccountUtils;
import com.ybkj.o2o.mc.common.Arith;
import com.ybkj.o2o.mc.common.DataGrid;
import com.ybkj.o2o.mc.common.query.EnterpriseQuery;
import com.ybkj.o2o.mc.entity.Enterprise;
import com.ybkj.o2o.mc.entity.Passenger;
import com.ybkj.o2o.mc.entity.PassengerAccount;
import com.ybkj.o2o.mc.manager.EnterpriseManager;
import com.ybkj.o2o.mc.service.EnterpriseService;
import com.ybkj.o2o.mc.service.PassengerAccountService;
import com.ybkj.o2o.mc.service.PassengerService;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by shine on 15/8/19.
 */
@Service
public class DefaultEnterpriseManager implements EnterpriseManager {

  @Autowired
  private EnterpriseService enterpriseService;

  @Autowired
  private PassengerService passengerService;

  @Autowired
  private PassengerAccountService passengerAccountService;

private List<Long> deleteList;

  @Override
  public boolean exists(String name, String appKey, Long companyId) {

    return enterpriseService.exists(name, appKey, companyId);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public Enterprise insert(Enterprise enterprise) {

    enterpriseService.insert(enterprise);

    return enterprise;
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public int batchInsert(List<Passenger> passengerList, Enterprise enterprise) {

    buildEnterprisePassengers(enterprise, passengerList);

    return passengerService.batchInsert(passengerList);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public int updatePassengers(List<Passenger> passengerList, Enterprise enterprise) {


    //原来的企业下所有的乘客
    List<Passenger> localPassengers = passengerService.findByEnterpriseAndAppkey(enterprise.getId(),
            enterprise.getAppKey());

//    int ret = 0;
//
//    if (!CollectionUtils.isEmpty(localPassengers)
//            && !CollectionUtils.isEmpty(passengerList)) { //同时存在新旧客户
//
//      //过滤出删除的客户
//      List<Long> deleteList = localPassengers.stream()
//              .filter(local -> !passengerList.contains(local))
//              .map(local -> local.getId())
//              .collect(Collectors.toList());
//      if (!CollectionUtils.isEmpty(deleteList)) {
//        ret += passengerService.batchDelete(deleteList);
//      }
//      
//      //过滤出新客户
//      List<Passenger> newList = passengerList.stream()
//              .filter(passenger -> !localPassengers.contains(passenger))
//              .collect(Collectors.toList());
//
//      //构造新数据
//      buildEnterprisePassengers(enterprise, newList);
//      if (!CollectionUtils.isEmpty(newList)) {
//        ret += passengerService.batchInsert(newList);
//      }
//
//      //过滤出旧客户
//      List<Passenger> oldList = passengerList.stream()
//              .filter(passenger -> localPassengers.contains(passenger))
//              .map(passenger -> {
//
//                Optional<Passenger> optional = localPassengers.stream()
//                        .filter(local -> local.getPhone().equals(passenger.getPhone()))
//                        .findFirst();
//
//                Passenger localPassenger = optional.get();
//                localPassenger.setName(passenger.getName());
//                localPassenger.setPlateNumber(passenger.getPlateNumber());
//
//                return localPassenger;
//              })
//              .collect(Collectors.toList());
//
//      passengerService.batchUpdate(oldList);
//
//    } else if (CollectionUtils.isEmpty(localPassengers)
//            && !CollectionUtils.isEmpty(passengerList)) { //只存在新客户
//      //保存所有新客户
//
//      buildEnterprisePassengers(enterprise, passengerList);
//
//      ret += passengerService.batchInsert(passengerList);
//
//
//    } else if (!CollectionUtils.isEmpty(localPassengers)
//            && CollectionUtils.isEmpty(passengerList)) { //只存在旧客户
//      //删除所有旧客户
//
//      List<Long> deleteList = localPassengers.stream()
//              .map(local -> local.getId())
//              .collect(Collectors.toList());
//
//      ret += passengerService.batchDelete(deleteList);
//
//    }
//
//    return ret;
    
  //童俊超修改开始
    //判断原客户和新客户是否为空
    List<Passenger> newList = new ArrayList<Passenger>();//新增加的客户
    deleteList = new ArrayList<Long>();
    List<Passenger> oldList = new ArrayList<Passenger>();//保留的老客户
    if(null != localPassengers && localPassengers.size()>0 && null != passengerList && passengerList.size()>0){
    	//遍历筛选出新增的客户,老客户 
    	for (int i = 0; i < passengerList.size(); i++) {
			if(null == passengerList.get(i).getId()){
				//id为空，新客户
				newList.add(passengerList.get(i));
			}else{
				//id不为空，老客户
				oldList.add(passengerList.get(i));
			}
		}
    	if(null != newList && newList.size()>0){
    		//新客户不为空，直接保存
    		buildEnterprisePassengers(enterprise, newList);//构造新数据
    		passengerService.batchInsert(newList);//保存新数据
    	}
    	if(null != oldList && oldList.size()>0){
    		//有老客户，判断老客户和原客户数量是否相等
    		if(oldList.size() == localPassengers.size()){//相等
    			//修改老客户基本信息
    			passengerService.batchUpdate(oldList);
    		}else{//不相等，筛选出已删除的老客户
    			String ids = "";//组装还存在的老客户ids
    			for (int i = 0; i < oldList.size(); i++) {
    				ids += ids + oldList.get(i).getId() + ",";
				}
    			//循环遍历原客户中已被删除的老客户到deleteList
    			for (int j = 0; j < localPassengers.size(); j++) {
					if(!ids.contains(localPassengers.get(j).getId().toString())){
						deleteList.add(localPassengers.get(j).getId());
					}
				}
    		}
    	}else{
    		//没有老客户，删除所有原客户信息
    		for (int i = 0; i < localPassengers.size(); i++) {
    			deleteList.add(localPassengers.get(i).getId());
			}
    	}
    	
    	if(null != deleteList && deleteList.size()>0){
			//删除已删除的老客户信息
			passengerService.batchDelete(deleteList);
		}
    }
    return 0;
    //童俊超修改结束
  }

  /**
   * 构造企业下乘客信息.
   *
   * @param enterprise    企业信息
   * @param passengerList 乘客列表
   */
  private void buildEnterprisePassengers(Enterprise enterprise, List<Passenger> passengerList) {
    for (Passenger p : passengerList) {
      if (StringUtils.isBlank(p.getName())) {
        p.setName("先生/女士");
      }
      p.setPhone(p.getPhone());
      p.setAppKey(enterprise.getAppKey());
      p.setAllowOverdraw(enterprise.getAllowOverdraw());
      p.setEnterpriseId(enterprise.getId());
      p.setEnterpriseName(enterprise.getName());
      p.setCompanyId(enterprise.getCompanyId());
      p.setCompanyName(enterprise.getCompanyName());
      if (p.getGender() == null) {
        p.setGender(1);
      }
      p.setDrawMoney(0d);
      p.setNodrawMoney(0d);
      p.setFrozenMoney(0d);
      p.setGradeId(enterprise.getGradeId());
      p.setGradeName(enterprise.getGradeName());
      p.setInBlackList(false);
      p.setType(1);
      p.setVersion(1);
    }
  }

  @Override
  public Enterprise findOne(Long enterpriseId, String appKey) {

    return enterpriseService.findByIdAndAppKey(enterpriseId, appKey);
  }

  @Override
  public Enterprise findByIdAndAppKey(Long enterpriseId, String appKey) {
    return enterpriseService.findByIdAndAppKey(enterpriseId, appKey);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public int update(Enterprise enterprise) {
    enterprise.setUpdated(new Date());
    return enterpriseService.updateEnterprise(enterprise);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public int deleteEnterprise(Long enterpriseId, String appKey) {

    List<Passenger> list = passengerService.findByEnterpriseAndAppkey(enterpriseId, appKey);
    
    if (!CollectionUtils.isEmpty(list)) {
      List<Long> passengers = list.stream().map(passenger -> passenger.getId())
              .collect(Collectors.toList());
      passengerService.batchDelete(passengers);
    }

    passengerService.deleteByEnterpriseAndAppkey(enterpriseId, appKey);

    return enterpriseService.delete(enterpriseId, appKey);
  }


  @Override
  public Enterprise fetch(Long id) {

    return enterpriseService.fetch(id);
  }


  @Override
  public DataGrid<Passenger> findEnterprisePassenger(Long id, int page, int rows) {

    List<Passenger> list = passengerService.findByEnterpriseForPage(id, page, rows);
    Long count = passengerService.countByEnterprise(id);

    DataGrid<Passenger> dataGrid = new DataGrid<>();
    dataGrid.setRows(list);
    dataGrid.setTotal(count);
    return dataGrid;
  }


  @Override
  @Transactional(rollbackFor = Exception.class)
  public PassengerAccount updateAccount(Enterprise enterprise, PassengerAccount account,
                                        boolean updateBlance, boolean useNoDrawMoney) {

    if (updateBlance) {
      AccountUtils.recharge(account, enterprise, useNoDrawMoney);

      int ret2 = enterpriseService.updateBalance(enterprise);
      if (ret2 != 1) {
        throw new RuntimeException("修改企业金额信息失败");
      }
    }

    account.setAfterDrawMoney(enterprise.getDrawMoney());
    account.setAfterNoDrawMoney(enterprise.getNodrawMoney());
    account.setCreated(new Date());
    account.setUpdated(new Date());
    account.setVersion(1);

    int ret = passengerAccountService.insert(account);
    if (ret != 1) {
      throw new RuntimeException("保存企业账户记录信息失败");
    }

    return account;
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public PassengerAccount accountNoDrawMoney(Enterprise enterprise, PassengerAccount account,
                                             boolean updateBlance) {

    if (updateBlance) {

      double balance = Arith.add(enterprise.getNodrawMoney(), account.getMoney());
      enterprise.setNodrawMoney(balance);

      int ret2 = enterpriseService.updateBalance(enterprise);
      if (ret2 != 1) {
        throw new RuntimeException("修改企业金额信息失败");
      }
    }

    account.setAfterDrawMoney(enterprise.getDrawMoney());
    account.setAfterNoDrawMoney(enterprise.getNodrawMoney());
    account.setCreated(new Date());
    account.setUpdated(new Date());
    account.setVersion(1);

    int ret = passengerAccountService.insert(account);
    if (ret != 1) {
      throw new RuntimeException("保存企业账户记录信息失败");
    }

    return account;
  }

  @Override
  public DataGrid<Enterprise> findByEnterpriseQuery(EnterpriseQuery enterpriseQuery) {
	try {
		List<Enterprise> list = enterpriseService.findByEnterpriseQuery(enterpriseQuery);
		Long count = enterpriseService.countByEnterpriseQuery(enterpriseQuery);
		DataGrid<Enterprise> dataGrid = new DataGrid<>();
		dataGrid.setRows(list);
		dataGrid.setTotal(count);
		return dataGrid;
		
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
	  }

  @Override
  public int updateCompanyName(Long companyId,String abbreviation, String appKey) {
    
    return enterpriseService.updateCompanyName(companyId,abbreviation,appKey);
  }

  @Override
  public int disposeGrade(Long gradeId, String gradeName, Long companyId, String appKey) {

    return enterpriseService.disposeGrade(gradeId,gradeName,companyId,appKey);
  }


}
